package cn.iocoder.an.module.business.service.drawconfig;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.an.framework.common.exception.ServerException;
import cn.iocoder.an.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.dal.dataobject.equipmentkeeptype.EquipmentKeepTypeDO;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.permission.PermissionService;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.iocoder.an.module.business.controller.admin.drawconfig.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.drawconfig.DrawConfigDO;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import cn.iocoder.an.module.business.dal.mysql.drawconfig.DrawConfigMapper;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.an.framework.common.util.collection.CollectionUtils.diffList;
import static cn.iocoder.an.module.business.enums.ErrorCodeConstants.*;

/**
 * 图号配置 Service 实现类
 *
 * @author zzy
 */
@Service
@Validated
public class DrawConfigServiceImpl implements DrawConfigService {

    @Resource
    private DrawConfigMapper drawConfigMapper;

    @Resource
    private PermissionService permissionService;

    @Resource
    private AdminUserService adminUserService;

    @Override
    public Long createDrawConfig(DrawConfigSaveReqVO createReqVO) {
        // 插入
        DrawConfigDO drawConfig = BeanUtils.toBean(createReqVO, DrawConfigDO.class);

        checkDrawConfig(createReqVO, "add");

        drawConfigMapper.insert(drawConfig);

        // 返回
        return drawConfig.getId();
    }

    @Override
    public void updateDrawConfig(DrawConfigSaveReqVO updateReqVO) {
        // 校验存在
        validateDrawConfigExists(updateReqVO.getId());
        checkDrawConfig(updateReqVO, "update");
        // 更新
        DrawConfigDO updateObj = BeanUtils.toBean(updateReqVO, DrawConfigDO.class);
        drawConfigMapper.updateById(updateObj);
    }


    public void checkDrawConfig(DrawConfigSaveReqVO reqVO, String type) {
        //根据用户名 图号 判断有无重复的图号 更新操作排除自身
        LambdaQueryWrapper<DrawConfigDO> queryWrapper = new LambdaQueryWrapper<DrawConfigDO>();
        queryWrapper.eq(DrawConfigDO::getCustomerAccount, reqVO.getCustomerAccount());
        queryWrapper.eq(DrawConfigDO::getDrawingNumber, reqVO.getDrawingNumber());

        if ("update".equals(type)) {
            queryWrapper.ne(DrawConfigDO::getId, reqVO.getId());
        }

        boolean exists = drawConfigMapper.exists(queryWrapper);
        if (exists) {
            throw exception("图号:" + reqVO.getDrawingNumber() + " 已存在!");
        }
    }

    @Override
    public void deleteDrawConfig(Long id) {
        // 校验存在
        validateDrawConfigExists(id);
        // 删除
        drawConfigMapper.deleteById(id);
    }

    @Override
    public void deleteDrawConfigListByIds(List<Long> ids) {
        // 删除
        drawConfigMapper.deleteByIds(ids);
    }


    private void validateDrawConfigExists(Long id) {
        if (drawConfigMapper.selectById(id) == null) {
            throw exception(DRAW_CONFIG_NOT_EXISTS);
        }
    }

    @Override
    public DrawConfigDO getDrawConfig(Long id) {
        return drawConfigMapper.selectById(id);
    }

    @Override
    public PageResult<DrawConfigDO> getDrawConfigPage(DrawConfigPageReqVO pageReqVO) {

        //判断是否是管理员
        if (permissionService.hasAnyRoles(SecurityFrameworkUtils.getLoginUserId(), "super_admin", "tenant_admin")) {//判断是不是管理员
            //查询全部
            if (StringUtils.isNotEmpty(pageReqVO.getCustomerAccount())) {
                pageReqVO.setCustomerAccount(pageReqVO.getCustomerAccount().trim());
            }
        } else {
            //查询自己的
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            AdminUserDO user = adminUserService.getUser(loginUserId);
            if (user == null) {//管理员切换租户无法查询到
                pageReqVO.setCustomerAccount(null);
            } else {
                String userName = user.getUsername();
                pageReqVO.setCustomerAccount(userName);
            }
        }

        return drawConfigMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DrawConfigDO> getDrawConfigListQuery(DrawConfigPageReqVO pageReqVO) {
        List<DrawConfigDO> all = drawConfigMapper.selectList();
        return all.stream()
                .collect(Collectors.toMap(
                        DrawConfigDO::getCustomerAccount,
                        Function.identity(),
                        BinaryOperator.maxBy(Comparator.comparing(DrawConfigDO::getCreateTime))
                ))
                .values()
                .stream()
                .toList();
    }

    @Override
    public List<DrawConfigDO> getDrawConfigList(DrawConfigPageReqVO pageReqVO) {
        LambdaQueryWrapperX<DrawConfigDO> queryWrapper = new LambdaQueryWrapperX<>();
        //判断是否是管理员
        if (permissionService.hasAnyRoles(SecurityFrameworkUtils.getLoginUserId(), "super_admin", "tenant_admin")) {//判断是不是管理员
            //查询全部
            pageReqVO.setCustomerAccount(null);
        } else {
            //查询自己的
            Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
            AdminUserDO user = adminUserService.getUser(loginUserId);
            if (user == null) {//管理员切换租户无法查询到
                pageReqVO.setCustomerAccount(null);
            } else {
                String userName = user.getUsername();
                pageReqVO.setCustomerAccount(userName);
                queryWrapper.eq(DrawConfigDO::getCustomerAccount, userName);
            }
        }

        return drawConfigMapper.selectList(queryWrapper);
    }

    @Override
    public ImportRespVO importList(List<DrawConfigImportVo> list, boolean isUpdateSupport) {
        // 1.1 参数校验
        if (CollUtil.isEmpty(list)) {
            throw exception(IMPORT_EQUIPMENT_MANAGE_NOT_EXISTS);
        }


        //2.记录成功或失败记录
        ImportRespVO respVO = ImportRespVO.builder().insertNameList(new ArrayList<>())
                .updateNameList(new ArrayList<>()).failureMap(new LinkedHashMap<>()).build();

        AtomicInteger count = new AtomicInteger(1);

        //
        List<DrawConfigDO> rusultList = new ArrayList<>();

        list.forEach(drawConfig -> {
            count.incrementAndGet();//记录行号

            // 2.1.2 校验名称
            if (StringUtils.isEmpty(drawConfig.getCustomerAccount())) {
                throw exception("第" + count + "行数据" + "客户账号不能为空!");
            }

            if (StringUtils.isEmpty(drawConfig.getDrawingNumber())) {
                throw exception("第" + count + "行数据" + "图号不能为空!");
            }

            //根据用户名 图号 判断有无重复的图号 更新操作排除自身
            LambdaQueryWrapper<DrawConfigDO> queryWrapper = new LambdaQueryWrapper<DrawConfigDO>();
            queryWrapper.eq(DrawConfigDO::getCustomerAccount, drawConfig.getCustomerAccount());
            queryWrapper.eq(DrawConfigDO::getDrawingNumber, drawConfig.getDrawingNumber());
            boolean exists = drawConfigMapper.exists(queryWrapper);
            if (exists) {
                throw exception("第" + count + "行数据" + "图号:" + drawConfig.getDrawingNumber() + " 已存在!");
            }
            rusultList.add(BeanUtils.toBean(drawConfig, DrawConfigDO.class));
            respVO.getInsertNameList().add(drawConfig.getCustomerAccount() + ":" + drawConfig.getDrawingNumber());
        });
        if (respVO.getFailureMap().size() > 0) {
            respVO.getInsertNameList().clear();
            return respVO;
        }
        //一次性保存
        drawConfigMapper.insertBatch(rusultList);

        return respVO;
    }

}